package com.fenrirtec.aepp.manage.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.AdvImageDto;
import com.fenrirtec.aepp.common.dto.SystemConfigDto;
import com.fenrirtec.aepp.common.service.AdvImageService;
import com.fenrirtec.aepp.common.service.FileService;
import com.fenrirtec.aepp.common.service.impl.AdvImageServiceImpl;
import com.fenrirtec.aepp.common.service.impl.FileServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.ImageUtils;

public class AdvImageUploadAction extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(AdvImageUploadAction.class);

	private File image;
	
	private String imageFileName;
	
	private String param;

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String ImageFileName) {
		this.imageFileName = ImageFileName;
	}

	public String getParam() {
		return param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	public AdvImageUploadAction() {
	}

	@Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
	    
	    FileService fileService = new FileServiceImpl();
	    AdvImageService advImageService = new AdvImageServiceImpl();
	    Boolean result = false;
		
		try {
			
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			String title = jsonObj.getString("title");
			String description = jsonObj.getString("description");
			
			BufferedImage sourceImg =ImageIO.read(new FileInputStream(image));
			int width = sourceImg.getWidth();
			int height = sourceImg.getHeight();
			long size = image.length();
			
			SystemConfigDto config = getSystemConfig();
			String uploadRootPath = config.getUploadRootFolder();
			String imagePath = config.getImagesSaveFolder();
			File saveFolder = new File(uploadRootPath, imagePath);
			if (!saveFolder.exists()) {
			    saveFolder.mkdirs();
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String fileName = sdf.format(new Date()) + imageFileName.substring(imageFileName.lastIndexOf("."));
			String path = uploadRootPath + imagePath + "/" + fileName;
			
			AdvImageDto advImageDto = new AdvImageDto();
			advImageDto.setDisplayOrder(0);
			advImageDto.setUseFlag(true);
			advImageDto.setTitle(title);
			advImageDto.setDescription(description);
			advImageDto.setPath(path);
			advImageDto.setWidth(width);
			advImageDto.setHeight(height);
			advImageDto.setSize(size);
			advImageDto.setCreateUser(getUserInfo().getLoginName());
			
			result = advImageService.insert(advImageDto);
			
			if (result) {
			    fileService.copyFile(image.getPath(), path);
			    image.deleteOnExit();
			}
			
			JSONObject root = new JSONObject();
			root.put("result", result);
			root.put("image", ImageUtils.imageToBase64(path));
			return root;

		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (FileNotFoundException e) {
		    if (logger.isErrorEnabled()) {
                logger.error("IO error occurred.", e);
            }
            throw new JSONActionStatusException(API.Common.Status.SERVER_ERROR, e);
        } catch (IOException e) {
            if (logger.isErrorEnabled()) {
                logger.error("IO error occurred.", e);
            }
            throw new JSONActionStatusException(API.Common.Status.SERVER_ERROR, e);
        }
	}
}
